<template>
  <basic-drawer
    :visible="visible"
    title="调整策略"
    ok-text="保存配置"
    @ok="handleSubmit"
    @open="handleBeforeOpen"
    @close="handleBeforeClose"
    @cancel="handleBeforeCancel">
    <div class="flex">
      <span class="adjust-strategy__title mr-4">域名</span>
      <CopyField :display="true" :mouse-over="true">
        {{ record.name }}
      </CopyField>
    </div>
    <a-divider margin="24px" type="dashed" />
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical">
      <a-form-item
        field="name"
        label="规则名称"
        asterisk-position="end"
        required>
        <a-input
          v-model="formData.name"
          :max-length="20"
          class="!w-100 mt-2"
          placeholder="请输入规则名称">
        </a-input>
      </a-form-item>
      <a-form-item label="匹配规则" asterisk-position="end" required>
        <matching-rule-view
          ref="matchingView"
          v-model="ruleGroups"
          class="w-full mt-2"></matching-rule-view>
      </a-form-item>

      <a-form-item
        field="name"
        label="执行策略"
        asterisk-position="end"
        required>
        <section class="flex flex-col">
          <div class="text-xs/5 text-5">规则生效时，执行指定动作</div>
          <a-select
            v-model="formData.name"
            class="!w-100 mt-2"
            placeholder="请选择执行策略"></a-select>
        </section>
      </a-form-item>

      <a-form-item
        field="name"
        label="响应类型"
        asterisk-position="end"
        required>
        <a-select
          v-model="formData.name"
          class="!w-100 mt-2"
          placeholder="请选择响应类型"></a-select>
      </a-form-item>

      <a-form-item
        field="name"
        label="响应代码"
        asterisk-position="end"
        required>
        <a-input
          v-model="formData.name"
          :max-length="20"
          class="!w-100 mt-2"
          placeholder="请输入响应代码">
        </a-input>
      </a-form-item>

      <a-form-item
        field="name"
        label="响应内容"
        asterisk-position="end"
        required>
        <a-textarea
          class="mt-2"
          placeholder="请输入响应内容"
          :auto-size="{ minRows: 5, maxRows: 5 }"
          allow-clear />
      </a-form-item>

      <a-form-item field="radio" label="状态" asterisk-position="end" required>
        <section class="flex flex-col">
          <a-radio-group v-model="formData.radio">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="2">禁用</a-radio>
          </a-radio-group>
        </section>
      </a-form-item>

      <!-- <a-form-item
        field="skip_module"
        label="路径"
        asterisk-position="end"
        required>
        <section class="flex flex-col">
          <span class="text-xs/5 text-5">规则生效时，执行指定动作</span>
          <a-checkbox-group v-model="formData.skip_module">
            <a-checkbox :value="1">自定义规则</a-checkbox>
            <a-checkbox :value="2">速率限制</a-checkbox>
          </a-checkbox-group>
        </section>
      </a-form-item>

      <a-form-item
        field="order"
        label="执行优先级"
        asterisk-position="end"
        required>
        <section class="flex flex-col">
          <a-select
            v-model="formData.order"
            placeholder="请选择执行优先级"
            class="!w-100"
            :options="priorityOptions" />
          <a-form-item
            v-if="formData.order === 2"
            field="priority"
            hide-label
            asterisk-position="end"
            class="!mb-0 mt-2"
            required>
            <a-select
              v-model="formData.priority"
              class="w-[336px]"
              placeholder="优先触发创建的规则，再触发选择的规则">
              <a-option
                v-for="item in custom_list"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </a-select>
          </a-form-item>
          <span v-if="formData.order === 2" class="text-5 text-xs/5"
            >在此规则前执行</span
          >
        </section>
      </a-form-item> -->
    </a-form>
  </basic-drawer>
</template>
<script lang="ts" setup>
import type { IMatchingGroup } from '@/components/MatchingRule/types'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import { v4 as uuidV4 } from 'uuid'
interface IProps {
  visible: boolean
  record?: any
}
const props = withDefaults(defineProps<IProps>(), {
  visible: false
})
interface IEmits {
  (e: 'update:visible', value: boolean): void
}
const emits = defineEmits<IEmits>()
const formRef = ref<FormInstance>()
const matchingView = ref()
const formData = ref({
  name: '',
  expression: '',
  radio: 1,
  expression_template: '',
  order: undefined,
  priority: undefined,
  skip_module: []
})
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    name: [
      {
        required: true,
        message: '请输入规则名称'
      }
    ],
    skip_module: [
      {
        required: true,
        message: '请选择执行动作'
      }
    ],
    order: [
      {
        required: true,
        message: '请选择执行优先级'
      }
    ],
    priority: [
      {
        required: true,
        message: '请选择自定义规则'
      }
    ]
  }
})
const ruleGroups = ref<IMatchingGroup[]>([
  {
    uuid: uuidV4(),
    rules: [
      {
        uuid: uuidV4(),
        field: '',
        operator: '',
        value: '',
        custom_field: ''
      }
    ]
  }
])

const getCustomRule = () => {
  // get_custom_list({ offset: 0, limit: 0 }).then((res: any) => {
  //   custom_list.value =
  //     res?.list.map((v) => {
  //       return Object.assign(
  //         {},
  //         {
  //           value: v.priority,
  //           label: v.name
  //         }
  //       )
  //     }) ?? []
  // })
}
watch(
  () => formData.value.order,
  (val) => {
    if (![0, 1].includes(val)) getCustomRule()
  },
  { deep: true }
)
// 获取详情
const getDetails = () => {
  // get_custom_detail({ id, with_node: 1 }).then((res) => {
  //   const { expression_template, node_list, ...params } =
  //     res as NodeWafRuleDetail
  //   Object.assign(formData.value, params)
  //   formData.value.node_id_list = getFieldsToArr(node_list, 'node_id')
  //   ruleGroups.value = JSON.parse(expression_template as string)
  // setTimeout(() => {
  //   const priorityArr = custom_list.value.map(
  //     (item: IPriority) => +item.value
  //   )
  // const min = Math.min(...priorityArr)
  // const max = Math.max(...priorityArr)
  // switch (+formData.value.priority!) {
  //   case min:
  //     formData.value.order = 1
  //     break
  //   case max:
  //     formData.value.order = 0
  //     break
  //   default:
  //     formData.value.order = 2
  // }
  // }, 100)
  // })
}
const handleBeforeOpen = async () => {
  if (props.record) {
    //getDetails(props.record?.id)
    getDetails()
    // formData.value.name = props?.record.name
  }
}
const handleBeforeClose = async () => {
  await formRef.value?.resetFields()
  emits('update:visible', false)
}

const handleBeforeCancel = () => {
  emits('update:visible', false)
}
function handleSubmit() {
  // await Promise.all([formRef.value?.validate(), matchingView.value.validate()])
  // const expression = matchingView.value?.generateTemplate() as string
  // const data: any = {
  //   ...omitReactive(formData.value, ['expression', 'expression_template'])
  //     .value,
  //   expression,
  //   expression_template: JSON.stringify(ruleGroups.value)
  // }
  // if (data.expression) {
  //   if (formData.value?.order === 1) {
  //     data.priority = 1
  //   } else if (formData.value?.order === 0) {
  //     if (route.params.id) {
  //       data.priority = custom_list.value.length
  //     } else {
  //       data.priority = custom_list.value.length + 1
  //     }
  //   } else if (formData.value?.order === 2) {
  //     data.priority = (formData.value?.priority as number) ?? 1
  //   }
  //   if (data?.id) {
  //     edit(data)
  //   } else {
  //     add(data)
  //   }
  // }
  // const error = await formRef.value?.validate()
  // if (error) return false
  // const apiPath = props.record ? 'updateGroup' : 'addGroup'
  // // 提交表单
  // return await apiPath({ ...formData })
  //   .then(() => {
  //     ToastUtils.success('修改成功')
  //     return Promise.resolve(true)
  //   })
  //   .catch(() => Promise.reject(false))
}
</script>

<style lang="less" scoped>
// :deep(.arco-form-item-label-col) {
//   @apply mb-0;
// }
.adjust-strategy__title {
  color: var(----1color-text-4, #8f959e);
  font-size: 14px;
  font-weight: 400;
  line-height: 22px; /* 157.143% */
}

.adjust-strategy__subtitle {
  color: var(----1color-text-2, #393c40);
  font-size: 14px;
  font-weight: 400;
  line-height: 22px; /* 157.143% */
  margin-left: 16px;
}
</style>
